package com.doraemon.staging.mvc.springmvc.view;

import com.doraemon.staging.webcontent.util.WebUtil;
import org.springframework.web.servlet.view.freemarker.FreeMarkerView;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;


/**
 * 支持环境变量 freemarker view.
 *
 * @author yangz
 * @date 2013-5-31 上午10:00:19
 */
public class EnvVarFreeMarkerView extends FreeMarkerView {

    private final static String VIEW_VAR_CTX = "CTX";

    private final static String VIEW_VAR_HOST_PATH = "HOST_PATH";

    private final static String VIEW_VAR_DEFAULT_JS_PATH = "DEFAULT_JS_PATH";

    private final static String VIEW_VAR_DEFAULT_CSS_PATH = "DEFAULT_CSS_PATH";


    @Override
    protected void exposeHelpers(Map<String, Object> model, HttpServletRequest request) throws Exception {
        String hostPath = WebUtil.getHostPath(request);
        model.put(VIEW_VAR_CTX, request.getContextPath());
        model.put(VIEW_VAR_HOST_PATH, hostPath);
        if (!"".equals(request.getContextPath())) {
            model.put(VIEW_VAR_DEFAULT_JS_PATH, (request.getContextPath() + "/template/" + request.getRequestURI().replace(request.getContextPath() + "/", "") + ".js").replace(".html.js", ".js"));
        } else {
            model.put(VIEW_VAR_DEFAULT_JS_PATH, ("/template/" + request.getRequestURI().substring(1) + ".js").replace(".html.js", ".js"));
        }
        if (!"".equals(request.getContextPath())) {
            model.put(VIEW_VAR_DEFAULT_CSS_PATH, (request.getContextPath() + "/template/" + request.getRequestURI().replace(request.getContextPath() + "/", "") + ".css").replace(".html.css", ".css"));
        } else {
            model.put(VIEW_VAR_DEFAULT_CSS_PATH, ("/template/" + request.getRequestURI().substring(1) + ".css").replace(".html.css", ".css"));
        }
    }

}
